package cmpe226.spring2011.project1;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import cmpe226.spring2011.project1.model.RecordDTO;

public class DataExtractor {

    public static Map<String, List<RecordDTO>> getData(String dir) {
        File testdir = new File(dir);
        return getData(Arrays.asList(testdir.listFiles()));
    }

    public static Map<String, List<RecordDTO>> getData(List<File> files) {
        Map<String, List<RecordDTO>> data = new HashMap<String, List<RecordDTO>>();
        
        // Traverse the file list to find stock symbols
        for (File symfile : files) {
            if (!symfile.getName().matches("\\w+\\.dat"))
                continue;
            
            String symbol = symfile.getName().replaceFirst("\\.dat", "");
            
            try {
                data.put(symbol, extractQuotes(symfile));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        
        return data;
    }

    private static List<RecordDTO> extractQuotes(File symfile) throws FileNotFoundException {
        List<RecordDTO> quotes = new ArrayList<RecordDTO>();
        Scanner lineScanner = new Scanner(symfile);
        
        // Skip non-important lines
        while (lineScanner.hasNextLine()) {
            if (lineScanner.nextLine().equals("Date,Open,High,Low,Close,Volume,Adj Close"))
                break;
        }
        
        // Grab the quotes
        while (lineScanner.hasNextLine()) {
            String[] fields = lineScanner.nextLine().split(",");
            quotes.add(new RecordDTO(fields));
        }
        
        return quotes;
    }

}
